<?php
/*
    NOR, simple feed agregator
    Copyright (C) 2011  Luis A. Arce González
    Copyright (C) 2011 	Víctor Ramírez 

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/


/* About this file
	All content logic is here.

*/

include_once("style.php");

///////////////////////////////////////////
///// Classes
///////////////////////////////////////////
class Pages{

	public static function index($user, $pub, $current_num, $entry){
		//FIGHT!

		Content::print_doc_header();
		
		Content::print_head(
			//Ttitle
			"NOR - Not another RSS", 
			//Imported javascript 
			array(
				'scripts/sha256.js',
				'scripts/jquery-1.6.4.js',
				'scripts/nor.js'
			),
			//Meta tags
			array(
				array(
					'name'   =>'author',
					'content'=>'Luis A. Arce'
				),
				array(
					'name'   =>'author',
					'content'=>'virako'
				)
			),
			//CSS linking
			array(
				array(
					'rel'  => 'stylesheet',
					'id'   => 'default_stylesheet',
					'href' => 'styles/default.css'
				),
                                array(
                                        'rel' => "icon",
                                        'href' =>"favicon.ico",
                                        'type' => "image/png\\"
                                )
			)
		);

		print(Pages::mainBody($user, $pub, $current_num, $entry));


		Content::finishhh_HIMMM//!!!!!
		();
	}

	//@param user Objeto de tipo user con la información del usuario que accede a la página
	public static function config($user, $config_pg, $entry){

		Content::print_doc_header();	
	
		Content::print_head(
			//Ttitle
			"NOR - Not another RSS | Config", 
			//Imported javascript 
			array(
				'scripts/sha256.js',
				'scripts/jquery-1.6.4.js',
				'scripts/nor.js'
			),
			//Meta tags
			array(
				array(
					'name'   =>'author',
					'content'=>'Luis A. Arce'
				),
				array(
					'name'   =>'author',
					'content'=>'virako'
				)
			),
			//CSS linking
			array(
				array(
					'rel'  => 'stylesheet',
					'id'   => 'default_stylesheet',
					'href' => 'styles/default.css'
				),
                                array(
                                        'rel' => "icon",
                                        'href' =>"favicon.ico",
                                        'type' => "image/png\\"
                                )
			)
		);

		print(Pages::configBody($user, $config_pg, $entry));
	
		Content::finishhh_HIMMM//!!!!!
		();
	}
	public static function register($action){
		Content::print_doc_header();	
	
		Content::print_head(
			//Title
			"NOR - Not another RSS | Register", 
			//Imported javascript 
			array(
				'scripts/sha256.js',
				'scripts/jquery-1.6.4.js',
				'scripts/nor.js'
			),
			//Meta tags
			array(
				array(
					'name'   =>'author',
					'content'=>'Luis A. Arce'
				),
				array(
					'name'   =>'author',
					'content'=>'virako'
				)
			),
			//CSS linking
			array(
				array(
					'rel'  => 'stylesheet',
					'id'   => 'default_stylesheet',
					'href' => 'styles/default.css'
				),
                                array(
                                        'rel' => "icon",
                                        'href' =>"favicon.ico",
                                        'type' => "image/png\\"
                                )


			)
		);

		print(Pages::registerBody($action));
	
		Content::finishhh_HIMMM//!!!!!
		();
	}


	/////////////////////////////
	///// Specific doc functions, the documents are changed here!
	/////////////////////////////
	//FIXME Maybe this kind of functions must be in Page class

	public static function mainBody($user, $pub, $current_num, $entry){

		//////// class declarations
		///header 
		$class_header = array(); 
		$class_header[0] = new Style(NULL, "header","img_header");
		$class_header[0]->addContentElms(HTML_content::DIV);

		///sidebar


		///timeline
		
		//////// Generates body snippet

		$body = "<body>\n";


		$body .= Content::get_header($user, $class_header);
		
		$body .= "\t<div id=\"content\">\n";

		$body .= Content::get_sidebar($user, NULL);

        $body .= Content::get_timeline($user, $current_num, 10, $pub, NULL, $entry);

	 	$body .= "\t</div>\n";

        $body .= "<div id=\"footer\">Copyright 2012. Luis A. Arce y Víctor Ramírez | <a href=\"?page=about\"> Acerca de</a></div>";

		$body .= "</body>\n";

		return $body;
	}

	public static function configBody($user, $config_pg, $entry){
	
		/////// Class declarations
		///header
		$class_header = array(); 
		$class_header[0] = new Style(NULL, "header","img_header");
		$class_header[0]->addContentElms(HTML_content::DIV);

		//////// Generates body snippet

		$body  = "<body>\n";

		$body .= Content::get_header($user, $class_header);
		

		$body .= Content::get_config_content($user, NULL, $config_pg, $entry);

		$body .="</body>\n";

		return $body;
	}

	public static function registerBody($action){
	
		/////// Class declarations
		///header
		$class_header = array(); 
		$class_header[0] = new Style(NULL, "header","img_header");
		$class_header[0]->addContentElms(HTML_content::DIV);

		//////// Generates body snippet

                global $error;
		$body  = "\t<body>\n";
		$body .= Content::get_header(NULL, $class_header);
		$body .= "\t\t<div id=\"content\">\n";
		if(isset($error['register']))
			$body .= "\t\t\t\t<div id=\"register_message\">" . $error['register'] . "</div>\n";
		else if($action != 'registered')
			$body .= Content::register_form(NULL);
		else
			$body .= "\t\t\t<div id=\"register_message\">El proceso de registro se completó satisfactoriamente</div>\n";

		$body .= "\t\t</div>\n";
		$body .="</body>\n";

		return $body;
	}
    
    public static function about($user){
        Content::print_doc_header();	
	
		Content::print_head(
			//Title
			"NOR - Not another RSS | About", 
			//Imported javascript 
			array(
				'scripts/sha256.js',
				'scripts/jquery-1.6.4.js',
				'scripts/nor.js'
			),
			//Meta tags
			array(
				array(
					'name'   =>'author',
					'content'=>'Luis A. Arce'
				),
				array(
					'name'   =>'author',
					'content'=>'virako'
				)
			),
			//CSS linking
			array(
				array(
					'rel'  => 'stylesheet',
					'id'   => 'default_stylesheet',
					'href' => 'styles/default.css'
				),
                                array(
                                        'rel' => "icon",
                                        'href' =>"favicon.ico",
                                        'type' => "image/png\\"
                                )
			)
		);

		print(Pages::aboutOf($user));
	
		Content::finishhh_HIMMM//!!!!!
		();
    }

    public static function aboutOf($user){
		$class_header = array(); 
		$class_header[0] = new Style(NULL, "header","img_header");
		$class_header[0]->addContentElms(HTML_content::DIV);

		$body = "<body>\n";


		$body .= Content::get_header($user, $class_header);
		
		$body .= "\t<div id=\"content\">\n";

		$body .= Content::get_sidebar($user, NULL);

        $body .= Content::get_about();

	 	$body .= "\t</div>\n";

        $body .= "<div id=\"footer\">Copyright 2012. Luis A. Arce y Víctor Ramírez <a href=\"?page=about\"> Acerca de</a></div>";

		$body .= "</body>\n";

		return $body;
    }
}

class Content{


	/////////////////////////////
	///// Reusable doc functions
	/////////////////////////////
	
	/**
		Applicable styles ids:
		(none)
	*/
	public static function print_doc_header(){
		/*print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");*/
		print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
		print("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
	}

	/**
		Applicable styles ids:
		(none)
	*/
	public static function print_head($title, $scripts, $metas, $links){

		print("<head>\n");
		print("\t<title>$title</title>\n");	
		
		foreach((array)$scripts as $script)
		//Google chrome does not recognizes auto-closed script tag altought is W3C valid
			printf("\t<script type=\"text/javascript\" src=\"%s\"/>\n", $script); 
			

		foreach((array)$metas as $metaAttr)
			Content::print_closed_tag('meta', $metaAttr);

		foreach((array)$links as $metaAttr)
			Content::print_closed_tag('link', $metaAttr);

		print("</head>\n");	
	}

	public static function register_form($class){

                global $error;

                $str = "\t\t\t\t<form id=\"register_form\" action=\"/nor/?page=register&amp;action=registered\" method=\"post\" onsubmit=\"return validateRegister();\">\n";
                $str .= "\t\t\t\t\t<p>\n";
                $str .= "\t\t\t\t\t\t<label id=\"register_email_label\" for=\"register_email\">Email</label>\n";
                $str .= "\t\t\t\t\t\t<input id=\"register_email\" type=\"text\" name=\"email\"/><br/>\n";
                $str .= "\t\t\t\t\t\t<label id=\"register_password_label\" for=\"register_password\">Contraseña</label>\n";
                $str .= "\t\t\t\t\t\t<input id=\"register_password\" type=\"password\"/><br/>\n";//this field is not sent, processed by javascript
                $str .= "\t\t\t\t\t\t<label id=\"register_repassword_label\" for=\"register_repassword\">Repita contraseña</label>\n";
                $str .= "\t\t\t\t\t\t<input id=\"register_repassword\" type=\"password\"/><br/>\n";//this field is not sent, processed by javascript
                $str .= "\t\t\t\t\t\t<input id=\"register_hashed_password\" type=\"hidden\" name=\"user_hash\"/>\n";
                $str .= "\t\t\t\t\t\t<div id=\"register_message\">";
                if(isset($error['register']))
                        $str .= $error['register'];
                $str .= "</div>\n";
                $str .= "\t\t\t\t\t\t<input type=\"submit\" value=\"Registrarse\" />\n";
                $str .= "\t\t\t\t\t</p>\n";
                $str .= "\t\t\t\t</form>\n";

		return $str;
	}
    
	/**
		Applicable styles ids:
		#header : 
	*/
	public static function get_header($user, $styles){
		
		$header = "<div id=\"img_header\"><a  id=\"url_header\" href=\"?page=main\" >Página principal</a></div>\n";
		//TODO: añadir DATA::GETBASEURL

		$header = Content::applyStyles($header, $styles);

		return "\t$header";
	}

	/**
		Applicable styles ids:
		#userInfo
		#login_email
		#login_password
		#login_hashed_password
	*/
	public static function get_user_info_sidebar($user, $styles){

                global $error;
		$str = "\t\t\t<div id=\"userInfo\">\n";

		if($user===NULL){
			$str .= "\t\t\t\t<form id=\"login_form\" action=\"/nor/?page=main&amp;action=login\" method=\"post\" onsubmit=\"return validateLogin();\">\n";
			$str .= "\t\t\t\t\t<p>\n";
			$str .= "\t\t\t\t\t\t<label id=\"login_email_label\" for=\"login_email\">Email</label>\n";
			$str .= "\t\t\t\t\t\t<input id=\"login_email\" type=\"text\" name=\"email\"/><br/>\n";
			$str .= "\t\t\t\t\t\t<label id=\"login_password_label\" for=\"login_password\">Contraseña</label>\n";
			$str .= "\t\t\t\t\t\t<input id=\"login_password\" type=\"password\"/><br/>\n";//this field is not sent, processed by javascript
			$str .= "\t\t\t\t\t\t<input id=\"login_hashed_password\" type=\"hidden\" name=\"user_hash\"/>\n";
			$str .= "\t\t\t\t\t\t<input type=\"submit\" value=\"Login\" />\n";
			$str .= "\t\t\t\t\t\t<a href=\"?page=register\">Registrarse</a>\n";
			$str .= "\t\t\t\t\t</p>\n";
			$str .= "\t\t\t\t</form>\n";
			$str .= "\t\t\t\t\t\t<div id=\"login_message\">";
                        if(isset($error['login']))
                                $str .= $error['login'];
                        $str .= "</div>\n";
		}else{
			$str .= "\t\t\t<div id=\"login_user_name\">$user->email</div>\n";
			$str .= "\t\t\t<a href=\"?page=config\">Configuración</a><br/>\n";
			$str .= "\t\t\t<a href=\"?action=logout\">Cerrar sesión</a><br/>\n";

		}

		$str .= "\t\t\t</div>\n";

		$str = Content::applyStyles($str, $styles);

		return $str;
	}
    
	public static function get_sidebar($user, $styles){
	
		$sortedFeeders;

		$sideBarSnippet  = "\t\t<div id=\"sideBar\">\n";
		$sideBarSnippet .= "\t\t\t<ul id=\"feedList\">\n";

		//If null, only subscribed or with editing priviledges feeds namer are shown
		if($user==NULL){
		    $list_pub = Publisher::get_publishers();	
		} 
                else    {
                    $list_pub = $user->get_subscriptions();
		}

		foreach($list_pub as $l_pub){
			$sideBarSnippet .= "\t\t\t\t<li class=\"feed\"><a href=\"?page=main&amp;feed=$l_pub->publisher_id\">$l_pub->name_p</a></li>\n";
		}

		$sideBarSnippet .= "\t\t\t</ul>\n";

                if($user===NULL){
                        $sideBarSnippet .= "\t\t\t<div id=\"rss_link\"><a  href=\"lib/rss.php\">RSS</a></div>\n";
                }else{
                        $sideBarSnippet .= "\t\t\t<div id=\"rss_link\"><a  href=\"lib/rss.php?user=" . $user->user_id . "\">RSS</a></div>\n";
                }

		$sideBarSnippet .= Content::get_user_info_sidebar($user, $styles);
		$sideBarSnippet .= "\t\t</div>\n";

		$sideBarSnippet = Content::applyStyles($sideBarSnippet, $styles);

		return $sideBarSnippet;
	}

	public static function get_config_sidebar($user, $styles, $config_pg){

		$sidebarSnippet  = "\t\t<div id=\"sideBar\">\n";
		
		$sidebarSnippet .= "\t\t\t<ul id=\"configMenu\">\n";

		$sidebarSnippet .= "\t\t\t\t<li class=\"";
		$sidebarSnippet .= ($config_pg===NULL||$config_pg==='personal')?'selItem': 'menItem';
		$sidebarSnippet .=  "\"><a href=\"?page=config&amp;config_pg=personal\">Personal</a></li>\n";

		$sidebarSnippet .= "\t\t\t\t<li class=\"";
		$sidebarSnippet .= ($config_pg==='feed')?'selItem': 'menItem';
		$sidebarSnippet .= "\"><a href=\"?page=config&amp;config_pg=feed\">Feed</a></li>\n";

		if($user->permission->is_writer()){
	           $sidebarSnippet .= "\t\t\t\t<li class=\"";
	           $sidebarSnippet .= ($config_pg==='publish')?'selItem': 'menItem';
	           $sidebarSnippet .= "\"><a href=\"?page=config&amp;config_pg=publish\">Publicar</a></li>\n";
		}
		if($user->permission->is_admin()){
                    $sidebarSnippet .= "\t\t\t\t<li class=\"";
                    $sidebarSnippet .= ($config_pg==='admin')?'selItem': 'menItem';
                    $sidebarSnippet .= "\"><a href=\"?page=config&amp;config_pg=admin\">Administración</a></li>\n";
		}
		$sidebarSnippet .= "\t\t\t</ul>\n";

		$sidebarSnippet .= "\t\t</div>\n";

		$sidebarSnippet = Content::applyStyles($sidebarSnippet, $styles);

		return $sidebarSnippet;

	}

	public static function get_config_content($user, $styles, $config_pg, $entry){
		
		$contentSnippet  = "\t<div id=\"content\">\n";

		$contentSnippet .= Content::get_config_sidebar($user, NULL, $config_pg);

		$contentSnippet .= "\t\t<div id=\"config_forms\">\n";

		switch($config_pg){
	        case 'feed':
                $contentSnippet .= Content::get_config_content_feed($user, $styles);
			    break;
		    case 'publish':
                $contentSnippet .= Content::get_config_content_publish($user, $styles, $entry, $del=NULL);
			    break;
            case 'publish_entry_deleted':
                $contentSnippet .= Content::get_config_content_publish($user, $styles, $entry, $del=2);
                break;
            case 'publish_entry_update':
                $contentSnippet .= Content::get_config_content_publish($user, $styles, $entry, $del=1);
                break;
            case 'publish_entry_create':
                $contentSnippet .= Content::get_config_content_publish($user, $styles, $entry, $del=0);
                break;
		    case 'admin':
                $contentSnippet .= Content::get_config_content_admin($user, $styles);
			    breaK;
		    default:
                $contentSnippet .= Content::get_config_content_personal($user, $styles);
			
		}

		$contentSnippet .= "\t\t</div>\n";

		$contentSnippet .= "\t</div>\n";

		$contentSnippet = Content::applyStyles($contentSnippet, $styles);

		return $contentSnippet;
	}

    public static function get_config_content_personal($user, $styles){

        global $error;

        // cambiar email
        $form  = "<form id=\"config_personal_email\" onsubmit=\"return validateChangeEmail();\" action=\"/nor/?page=config&amp;config_pg=personal&amp;action=change_email\" method=\"post\">\n";
        $form .= "<fieldset><legend> Cambiar email</legend>\n";
        
        $form .= "<p><label id=\"email_label\" for=\"change_input_email\" >Email (nuevo)</label>\n";
        $form .= "<input id=\"change_input_email\" type=\"text\" name=\"email\"/></p>\n";

        $form .= "<p><label id=\"email_label2\" for=\"change_input_email2\">Repetir email (nuevo)</label>\n";
        $form .= "<input id=\"change_input_email2\" type=\"text\"/></p>\n";

        $form .= "<p><label id=\"password_label_email\" for=\"password\">Contraseña </label>\n";
        $form .= "<input id=\"password\" type=\"password\"/></p>\n";
        $form .= "<input id=\"change_input_user_hash\" type=\"hidden\" name=\"re_user_hash\"/>\n";
        $form .= "<div id=\"change_input_message\">";
        if(isset($error['change_mail']))
                $form .= $error['change_mail'];
        $form .= " </div>\n";
        $form .= "<input id=\"change_mail\" type=\"submit\" value=\"Cambiar\"/> \n";

        $form .= "</fieldset>\n";
        $form .= "</form>\n";
        
        // cambiar pass
        $form .= "<form id=\"config_personal_pass\" onsubmit=\"return validateChangePassword();\" action=\"/nor/?page=config&amp;config_pg=personal&amp;action=change_pass\" method=\"post\" >\n";
        $form .= "<fieldset><legend> Cambiar contraseña</legend>\n";
        
        $form .= "<p><label id=\"password_label\" for=\"change_input_pass1\">Contraseña (actual)</label>\n";
        $form .= "<input id=\"change_input_pass1\" type=\"password\"/></p>\n";
        
        $form .= "<p><label id=\"password_label2\" for=\"change_input_pass_new\">Contraseña (nueva)</label>\n";
        $form .= "<input id=\"change_input_pass_new\" type=\"password\"/></p>\n";

        $form .= "<p><label id=\"repassword_label_2\" for=\"repassword2\"> Repetir contraseña (nueva)</label>\n";
        $form .= "<input id=\"repassword2\" type=\"password\"/></p>\n";

        $form .= "<input id=\"change_input_pass_hash\" type=\"hidden\" name=\"re_user_hash\"/>\n";
        $form .= "<input id=\"change_input_pass_new_hash\" type=\"hidden\" name=\"new_user_hash\"/>\n";
        $form .= "<div id=\"change_input_pass_message\">";
        if(isset($error['change_pass']))
                $form .= $error['change_pass'];
        $form .= "</div>\n";

        $form .= "<input id=\"change_pass\" type=\"submit\" value=\"Cambiar\"/> \n";

        $form .= "</fieldset>";
        $form .= "</form>";


        // cambiar opciones de comparticion
        $form .= "<form id=\"config_personal_sharing\" action=\"/nor/?page=config&amp;config_pg=personal&amp;action=change_sharing\"  method=\"post\" >\n";
        $form .= "<fieldset><legend> Opciones de compartición</legend>\n";

        $form .= "<input id=\"sharing_opt\" name=\"sharing_opt\" type=\"checkbox\" "; 
        if ($user->sharing)
            $form .= "checked=\"checked\"/>";
        else
            $form .= "/>";
        $form .= "<label  for=\"sharing_opt\">Compartir_rss</label>";
        
        $form .= "<input id=\"change_sharing\" type=\"submit\" value=\"Cambiar\"/> \n";

        $form .= "</fieldset>";
        $form .= "</form>";



        
        return $form;
    }

    public static function get_config_content_feed($user, $styles){

        global $error;

        $publishers = Publisher::get_publishers();
        if (count($publishers) > 0){
            // ir cuando clikemos a config=feed de nuevo
            $form = "<form id=\"config_feed\" action=\"/nor/?page=config&amp;config_pg=feed&amp;action=change_feed\" method=\"post\">";
            $form .= "<fieldset><legend> Configuración de entradas</legend>";
            foreach ($publishers as $pub){
                $id_pub = $pub->publisher_id;
                $name   = $pub->name_p; 
                if ($user->is_subscripter_to($pub))
                    $form .= "<p><input id=\"pub_$id_pub\" name=\"pub_$id_pub\" type=\"checkbox\" checked=\"checked\"/>";
                else
                    $form .= "<p><input id=\"pub_$id_pub\" name=\"pub_$id_pub\" type=\"checkbox\" />";
                $form .= "<label for=\"pub_$id_pub\">$name</label></p>";
            }
                $form .= "<input id=\"config_feed_submit\" type=\"submit\" value=\"Cambiar configuración\" />";
                
            $form .= "<div id=\"config_feed_message\">";
            if(isset($error['change_feed']))
                    $form .= $error['change_feed'];
            $form .= "</div>\n";
            $form .= "</fieldset></form>";
            }
            else
                $form = "No existen publicadores.";
        return $form;
    }

    public static function get_config_content_publish($user, $styles, $entry, $del){

        global $error;

        if ($del != NULL and $del==2){
            $form = "La entrada ha sido eliminada."; 
        }
        elseif ($del != NULL and $del==1){
            $form = "La entrada ha sido actualizada."; 
        }
        elseif ($del != NULL and $del==0){
            $form = "La entrada ha sido creada."; 
        }
        elseif ($entry[0] == 1){
            // get entry
            $current_entry = $entry[1];
            $form = "<form id=\"update_entry1\" action=\"/nor/?page=config&amp;config_pg=publish_entry_update&amp;edit=$current_entry->entry_id&amp;action=update_entry\" method=\"post\">";
            $form .= "<fieldset><legend> Actualizar entrada</legend>";

            $form .= "<input type=\"text\" name=\"title_entry_u\" value=\"$current_entry->title_e\"/>";
            $form .= "<p><textarea name=\"text_entry_u\" rows=\"15\" cols=\"80\">$current_entry->content_e</textarea></p>";
            $form .= "<div id=\"update_entry_message\">";
            if(isset($error['update_entry']))
                $form .= $error['update_entry'];
            $form .= "</div>\n";
            $form .= "<input id=\"update_entry\" type=\"submit\" value=\"Actualizar\" />";
            $form .= "</fieldset></form>";
        }
        elseif ($entry[0] == 2){
            $current_entry = $entry[1];
            $form = "<form id=\"del_entry\" action=\"/nor/?page=config&amp;config_pg=publish_entry_deleted&amp;del=$current_entry->entry_id&amp;action=del_entry\" method=\"post\">";
            $form .= "<div id=\"text_del\" >Está seguro de que quiere eliminar la entrada \"$current_entry->title_e\"";
            $form .= "<input name=\"del_entry_yes\" type=\"submit\" value=\"Si\" /></div>";
            $form .= "</form>";

        }    
        elseif ($entry[0] == 0){

            $form = "<form id=\"add_entry1\" action=\"/nor/?page=config&amp;config_pg=publish_entry_create&amp;action=add_entry\" method=\"post\">";
            $form .= "<fieldset><legend> Crear nueva entrada</legend>";
            
            // Publishers
            $publishers = $user->get_write_publishers();
            $form .= "<select id=\"pub_entry\" name=\"pub_entry\" size=\"1\">";
            foreach ($publishers as $publisher){
               $name = $publisher->name_p;
               $form .= "<option value=\"$name\"> $name </option>";
            }
            $form .= "</select>";
            $form .= "<input type=\"text\" name=\"title_entry\" value=\"Título\"/>";
            $form .= "<p><textarea name=\"text_entry\" rows=\"15\" cols=\"80\"> </textarea></p>";
            $form .= "<div id=\"add_entry_message\">";
            if(isset($error['add_entry']))
                    $form .= $error['add_entry'];
            $form .= "</div>\n";
            $form .= "<input id=\"add_entry2\" type=\"submit\" value=\"Crear entrada\" />";

            $form .= "</fieldset></form>";
        }

        return $form;
        
    }

    public static function get_config_content_admin($user, $styles){
        
        global $error;

        //// add publisher
        $form = "<form id=\"add_publisher2\" action=\"/nor/?page=config&amp;config_pg=admin&amp;action=add_publisher\" method=\"post\">\n";
        $form .= "<fieldset><legend> Añadir Publicador</legend>\n";

        $form .= "<label for=\"title_pub\">Titulo</label>\n";
        $form .= "<input id=\"title_pub\" type=\"text\" name=\"title_pub\" />\n";
        $form .= "<p><label for=\"dir_rss\">RSS</label>\n";
        $form .= "<input id=\"dir_rss\" type=\"text\" name=\"dir_rss\" /></p>\n";
        $form .= "<p><label for=\"url\">Dirección web</label>\n";
        $form .= "<input id=\"url\" type=\"text\" name=\"url\" /></p>\n";
        $form .= "<p><label for=\"descrip_pub\">Descripción</label>\n";
        $form .= "<textarea id=\"descrip_pub\" name=\"descrip_pub\" rows=\"5\" cols=\"60\"> </textarea></p>\n";
        $form .= "<div id=\"add_publisher\">";
        if(isset($error['add_publisher']))
                $form .= $error['add_publisher'];
        $form .= "</div>\n";
        $form .= "<p><input id=\"add_entry\" type=\"submit\" value=\"Añadir publicador\"/> </p>\n";

        $form .= "</fieldset></form>\n";

        ////remove publisher 
        $form .= "<form id=\"del_pub_form\" action=\"/nor/?page=config&amp;config_pg=admin&amp;action=del_publisher\" method=\"post\">\n";
        $form .= "<div id=\"del_publisher_message\">";
        if(isset($error['del_publisher']))
                $form .= $error['del_publisher'];
        $form .= "</div>\n";
        $form .= "<fieldset><legend> Eliminar publicador</legend>\n";
        
        // get_publishers
        $publishers = Publisher::get_publishers();
        $form .= "<select id=\"del_publishers\" name=\"del_pub\" size=\"1\">\n";
        foreach ($publishers as $pub){
           $name = $pub->name_p;
           $form .= "<option value=\"$name\"> $name </option>\n";
        }
        $form .= "</select>\n";
        $form .= "<input id=\"del_pub_submit\" type=\"submit\" value=\"Eliminar\"/> \n";
        $form .= "</fieldset></form>\n";


        //// change permission
        $form .= "<form id=\"config_admin\" action=\"/nor/?page=config&amp;config_pg=admin&amp;action=change_per\" method=\"post\">\n";
        $form .= "<div id=\"change_per_message\">";
        if(isset($error['change_per']))
                $form .= $error['change_per'];
        $form .= "</div>\n";
        $form .= "<fieldset><legend> Configuración de permisos</legend>\n";
        
        // Option add/quit
        $form .= "<select id=\"add_quit\" name=\"add_quit\" size=\"1\">\n";
        $form .= "<option value=\"Dar\"> Dar </option>\n";
        $form .= "<option value=\"Quitar\"> Quitar </option>\n";
        $form .= "</select>\n";

        // get_users
        $users = User::get_names_users();
        $form .= "<select id=\"user_per\" name=\"user_per\" size=\"1\">\n";
        foreach ($users as $email){
           $email = $email[0];
           $form .= "<option value=\"$email\"> $email </option>\n";
        }
        $form .= "</select>\n";

        // Publishers without permissions
        $publishers = Publisher::get_publishers();
        $form .= "<select id=\"publishers\" name=\"pub_per\" size=\"1\">\n";
        foreach ($publishers as $pub){
           $name = $pub->name_p;
           $form .= "<option value=\"$name\"> $name </option>\n";
        }
        $form .= "</select>\n";
        $form .= "<input id=\"config_admin_submit1\" type=\"submit\" value=\"Aplicar\"/>\n";
        $form .= "</fieldset></form>\n";

        //// Add new user from admin config page
        $form .= "<form id=\"config_admin3\" onsubmit=\"return validateAdminNewUser();\" action=\"/nor/?page=config&amp;config_pg=admin&amp;action=add_user\" method=\"post\">\n";
        $form .= "<fieldset><legend> Añadir usuario</legend>\n";
        $form .= "<p><label id=\"email_label\" for=\"new_email\">Email</label>\n";
        $form .= "<input id=\"new_email\" name=\"new_email\" type=\"text\"/></p>\n";
        $form .= "<p><label id=\"password_label1\" for=\"password1\">Contraseña</label>\n";
        $form .= "<input id=\"password1\" name=\"pass_add\" type=\"password\"/></p>\n";
        $form .= "<p><label id=\"password_label2\" for=\"password1\">Repite contraseña</label>\n";
        $form .= "<input id=\"password2\" name=\"pass_add\" type=\"password\"/></p>\n";
        $form .= "<div id=\"admin_new_user_message\"></div>\n";
        $form .= "<input id=\"new_user_hash\" type=\"hidden\" name=\"new_user_hash\"/>\n";

        $form .= "<input id=\"config_admin_submit2\" type=\"submit\" value=\"Añadir\"/>\n";
        $form .= "</fieldset></form>\n";


        //// remove user
        $form .= "<form id=\"config_admin2\" action=\"/nor/?page=config&amp;config_pg=admin&amp;action=del_user\" method=\"post\">\n";
        $form .= "<fieldset><legend> Eliminar usuario</legend>\n";
        $users = User::get_names_users();
        $form .= "<select id=\"user_del\" name=\"user_del\" size=\"1\">\n";
        foreach ($users as $email){
           $email = $email[0];
           $form .= "<option value=\"$email\"> $email </option>\n";
        }
        $form .= "</select>\n";
        $form .= "<input id=\"config_admin_submit3\" type=\"submit\" value=\"Eliminar\"/>\n";
        $form .= "</fieldset></form>\n";

        return $form;
    }


	/**
		Applicable styles ids:
		#timeline     : all timeline division
		Applicable class names
		@entry        : all entry division
		@entry_title  :
		@entry_author :
		@entry_date   : //TODO: it would be great to use there the new HTML5 tag "time", but no browser seems to support it
		@entry_content: content of the entry, it could content some html tags. //TODO: study allowed tags
	*/
	public static function get_timeline($user, $current_num, $max_size, $pub, $styles, $entry){

		$timeLineSnippet = "\t\t<div id=\"timeLine\">\n";
        
        if ($entry[0] != NULL){
            switch($entry[0]){
            case '2': // del_entry
                $timeLineSnipeet .= Content::get_del_entry($entry[1]);
                break;
            case '1': // edit_enty
                $timeLineSnipeet .= Content::get_edit_entry($entry[1]);
                break;
            case '0': // show_entry
                $c_pub = new Publisher($c_entry->publisher_id);
                $c_entry = $entry[1];
		$timeLineSnippet .= "\t\t\t<div class=\"entry\">\n" ;
		$timeLineSnippet .= "\t\t\t\t<div class=\"entry_title\"><a href=\"?page=main&amp;entry=$c_entry->entry_id\">$c_entry->title_e</a></div>\n" ;
		$timeLineSnippet .= "\t\t\t\t<div class=\"entry_author\"><a href=\"$c_pub->url\">$c_pub->name_p</a></div>\n" ;
		$timeLineSnippet .= "\t\t\t\t<div class=\"entry_date\">$c_entry->date</div>\n" ;
		$timeLineSnippet .= "\t\t\t\t<div class=\"entry_content\"><p>$c_entry->content_e</p></div>\n";
                if ($user != null and $user->is_writer_of($c_pub)){
                    $timeLineSnippet .= "\t\t\t<div class=\"manage_entry>\n";
                    $timeLineSnippet .= "\t\t\t\t<div class=\"edit_entry\">";
                    $timeLineSnippet .= "<a href=\"?page=config&amp;config_pg=publish&amp;edit=$c_entry->entry_id\">Editar</a></div>\n";   
                    $timeLineSnippet .= "\t\t\t\t<div class=\"del_entry\">";
                    $timeLineSnippet .= "<a href=\"?page=config&amp;config_pg=publish&amp;del=$c_entry->entry_id\">Eliminar</a></div>\n";   
                    $timeLineSnippet .= "\t\t\t</div>\n";
                }
		$timeLineSnippet .= "\t\t\t</div>\n";
                break;
		    }
            return $timeLineSnippet;
        }
        
        $num_ini = ($current_num)*$max_size;
        $num_fin = $num_ini + $max_size;
        if ($pub != NULL){
            $pubs = array($pub);
            extract(Entry::get_entries_restricted_pub_limit($pubs, $num_ini, $num_fin));
        }
        else{
            if($user==NULL){
                extract(Entry::get_entries_limit($num_ini, $num_fin));
            }
            else {
                $pubs = $user->get_subscriptions();
                extract(Entry::get_entries_restricted_pub_limit($pubs, $num_ini, $num_fin));
            }
        }

        $current_entries = $value_extract_1;
        $size_entries    = $value_extract_2;

        foreach ($current_entries as $c_entry){
                $c_pub = new Publisher($c_entry->publisher_id);
		$timeLineSnippet .= "\t\t\t<div class=\"entry\">\n" ;
		$timeLineSnippet .= "\t\t\t\t<div class=\"entry_title\"><a href=\"?page=main&amp;entry=$c_entry->entry_id\">$c_entry->title_e</a></div>\n" ;
		$timeLineSnippet .= "\t\t\t\t<div class=\"entry_author\"><a href=\"$c_pub->url\">$c_pub->name_p</a></div>\n" ;
		$timeLineSnippet .= "\t\t\t\t<div class=\"entry_date\">$c_entry->date</div>\n" ;
	        $timeLineSnippet .= "\t\t\t\t<div class=\"entry_content\"><p> $c_entry->content_e</p></div>\n";
                if ($user != null and $user->is_writer_of($c_pub)){
                        $timeLineSnippet .= "\t\t\t\t<div class=\"manage_entry\">\n";
                        $timeLineSnippet .= "\t\t\t\t\t<div class=\"edit_entry\">";
                        $timeLineSnippet .= "<a href=\"?page=config&amp;config_pg=publish&amp;edit=$c_entry->entry_id\">Editar</a></div>\n";   
                        $timeLineSnippet .= "\t\t\t\t\t<div class=\"del_entry\">";
                        $timeLineSnippet .= "<a href=\"?page=config&amp;config_pg=publish&amp;del=$c_entry->entry_id\">Eliminar</a></div>\n";   
                        $timeLineSnippet .= "\t\t\t\t</div>\n";
                }
		$timeLineSnippet .= "\t\t\t</div>\n";
        
	}
        $timeLineSnippet .= "\t\t\t</div>\n";

        $timeLineSnippet .= "\t<div id=\"navigator\">\n";
        $timeLineSnippet .= Content::get_bar_navigation($current_num, $size_entries, $max_size, $pub);
		$timeLineSnippet .= "\t</div>\n";
	
		$timeLineSnippet = Content::applyStyles($timeLineSnippet, $styles);

		return $timeLineSnippet;

	}

    public static function get_about(){
        $timeLineSnippet = "\t\t<div id=\"about\">\n";
		$timeLineSnippet .= "\t\t\t\t <h1>NOR²: Not Other RSS Reader.</h1>  \n";
		$timeLineSnippet .= "\t\t\t\t <p>La finalidad de esta página web es
        recolectar mediante un agregador de contenidos RSS las publicaciones de las asociaciones
        y organismos de la Escuela Técnica Superior de Ingeniería Informática.</p>\n"; 
		$timeLineSnippet .= "\t\t\t\t <p> De esta manera, el usuario que quiera informarse
                de las noticias y publicaciones de las asociaciones de su facultad podrá hacerlo 
                desde el mismo portal, sin tener que visitar cada una de las páginas de las asociaciones
                o agregarlas una a una a un lector RSS.</p> ";
                $timeLineSnippet .= "\t\t\t\t<p>Provee además funciones de edición y publicación
                de entradas para todos aquellos organismos que no tengan una plataforma RSS, y permite
                obtener un fichero de sindicación personalizado para que cada usuario pueda suscribirse 
                a las asociaciones que quiera de manera fácil a través de la plataforma usando su lector
                RSS preferido.</p>\n";
		$timeLineSnippet .= "\t\t\t\t <p>De cara al al futuro, NOR² pretende convertirse en una
                generalista para la lectura y publicación de entradas, un blog con mucho enfoque a la 
                sindicación.</p>\n";
        $timeLineSnippet .= "\t\t\t</div>\n";
        return $timeLineSnippet;
        
    }

    public static function get_bar_navigation($current_num, $size_entries, $max_size, $pub){
        if (intval(($size_entries - 1) / $max_size) <= $current_num)
            $next = false;
        else
            $next = true;
        if ($current_num <= 0)
            $previous = false;
        else
            $previous = true;

        $c_num_pre  = $current_num - 1;  
        $c_num_next = $current_num + 1;

		$str = "";

        if ($pub != null){
            $feed = $pub->publisher_id; 
            if ($previous)
                $str .= "\t<a id=\"navigate_left\" href=\"?page=main&amp;feed=$feed&amp;nav=$c_num_pre\">Anterior</a>";
            if ($next)
                $str .= "\t<a id=\"navigate_right\" href=\"?page=main&amp;feed=$feed&amp;nav=$c_num_next\">Siguiente</a>";
        }
        else{
            if ($previous)
                $str .= "\t<a id=\"navigate_left\" href=\"?page=main&amp;nav=$c_num_pre\">Anterior</a>";
            if ($next)
                $str .= "\t<a id=\"navigate_right\" href=\"?page=main&amp;nav=$c_num_next\">Siguiente</a>";
        }

        return $str;
    }

	/**
		Applicable styles ids:
		(none)
	*/
    
	public static function finishhh_HIMMM//!!!!!
	(){
		print("</html>\n");
	}

	/////////////////////////////
	///// Auxliriary functions
	/////////////////////////////

	private static function applyStyles($snippet, $styles){

		if($styles!==NULL){
			foreach($styles as $style){
				$snippet = $style->apply($snippet);
			}
		}

		return $snippet;

	}

	private static function print_closed_tag($name, $attrs){
		
		print("\t<$name ");	
		foreach($attrs as $attName=>$attValue)
			print("$attName=\"$attValue\" ");
		print("/>\n");
		//FIXME for Google chrome singleton tag closing
		//print("></$name>\n");
	}
}


///////////////////////////////////////////
///// Enumerations
///////////////////////////////////////////

abstract class HTML_ {
	public static function getSelectedArrayString($docElms){

		$selected = array();
		
		$cons = new ReflectionClass(get_called_class());
		
		foreach($cons->getConstants() as $name=>$value){

			if(($docElms & $value) == $value){
				array_push($selected, strtolower($name));
			}
		}

		return $selected;
	}
}

class HTML_doc extends HTML_{
	
	const LINK  = 0x01;
	const BODY  = 0x02;
	const HEAD  = 0x04;
	const META  = 0x08;
	const STYLE = 0x10;
}

/**
	From XHTML DTD
*/
class HTML_content extends HTML_{

	const DIV  = 0x1;
	const SPAN = 0x2;

	//Text emphasis
	const STRONG = 0x04;
	const EM     = 0x08;
	const A      = 0x10;
	const BIG    = 0x20;
	const SMALL  = 0x40;

	//Text blocks
	const P      = 0x080;
	const PRE    = 0x100;
	const CODE   = 0x200;

	//Headings
	const H1 = 0x0400;
	const H2 = 0x0800;
	const H3 = 0x1000;
	const H4 = 0x2000;
	const H5 = 0x4000;
	const H6 = 0x8000;

	//Lists
	const OL = 0x010000;
	const UL = 0x020000;

	const LI = 0x040000;
	
	const DL = 0x080000;
	const DT = 0x100000;
	const DD = 0x200000;

	//Other
	const ADDRESS = 0x04000000;
	const HR      = 0x08000000;
	const BR      = 0x10000000;
	const IMG     = 0x20000000;

	//More will be added if needed
}

class HTML_form extends HTML_{

	//Forms
	const FORM     = 0x0040000;

	const LABEL    = 0x0080000;
	const INPUT    = 0x0100000;
	const SELECT   = 0x0200000;
	const OPTGROUP = 0x0400000;
	const OPTION   = 0x0800000;
	const TEXTAREA = 0x1000000;
	
	const FIELDSET = 0x2000000;
	const LEGEND   = 0x4000000;

	const BUTTON   = 0x8000000;
}

class HTML_table extends HTML_{

	//Table elements
	const TABLE = 0x10000000;
	const TD    = 0x20000000;
	const TH    = 0x40000000;
	const TR    = 0x80000000;

}


?> 

